class ChangePwd {
    constructor() {
        this.form = document.querySelector('#changePwdForm');
        this.oldPassword = document.querySelector('#oldPassword');
        this.newPassword = document.querySelector('#newPassword');
        this.confirmPassword = document.querySelector('#confirmPassword');
        
        this.init();
    }

    init() {
        this.checkLoginStatus();
        this.bindEvents();
    }

    // 检查登录状态
    checkLoginStatus() {
        const token = localStorage.getItem('token');
        if (!token) {
            alert('请先登录！');
            window.location.href = 'login.html';
        }
    }

    // 表单验证
    validate() {
        // 原密码验证
        if (!this.oldPassword.value) {
            alert('请输入原始密码');
            return false;
        }

        // 新密码验证
        if (!this.newPassword.value) {
            alert('请输入新密码');
            return false;
        }
        if (!/\w{6,12}/.test(this.newPassword.value)) {
            alert('新密码必须是6-12位字母数字下划线');
            return false;
        }

        // 确认密码验证
        if (!this.confirmPassword.value) {
            alert('请确认新密码');
            return false;
        }
        if (this.newPassword.value !== this.confirmPassword.value) {
            alert('两次输入的新密码不一致');
            return false;
        }

        return true;
    }

    bindEvents() {
        this.form.addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleSubmit();
        });
    }

    // 处理表单提交
    async handleSubmit() {
        if (!this.validate()) return;

        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
        const token = localStorage.getItem('token');

        try {
            const response = await fetch('http://localhost:8888/users/rpwd', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'authorization': token
                },
                body: new URLSearchParams({
                    id: userInfo.id,
                    oldPassword: this.oldPassword.value,
                    newPassword: this.newPassword.value,
                    rNewPassword: this.confirmPassword.value
                })
            });

            const data = await response.json();
            
            if (data.code === 1) {
                alert('修改密码成功，请重新登录！');
                // 清除登录信息
                localStorage.removeItem('token');
                localStorage.removeItem('userInfo');
                window.location.href = 'login.html';
            } else {
                alert(data.message || '修改密码失败，请重试');
            }
        } catch (error) {
            alert('修改密码失败，请检查网络连接');
            console.error('修改密码错误：', error);
        }
    }
}

// 初始化修改密码功能
document.addEventListener('DOMContentLoaded', () => {
    new ChangePwd();
}); 